import {ReactElement} from './ReactElement'

function mapChildren(children, func, context) {
    //TODO实现此mapChildren方法
    let result = []
    for(let i = 0,len =children.length;i < len; i++) {
        let child = children[i]
        let newEl = null
        if(Array.isArray(child)) {
            child.forEach((item, index)=>{
                let oldkey = item.key ? item.key : i
                newEl = func(child, i)
                newEleChange(result, newEl, oldkey)
                console.log(oldkey)
            })
        }else{
            let oldkey = child.key ? child.key : i
            newEl = func(child, i)
            newEleChange(result, newEl, oldkey)
            console.log(oldkey)
        }
        
    }
    console.log(result, 'jieguo')
    return result; 
}

// key的算法不懂怎么弄
function newEleChange(result, newEl, oldkey){
    if(Array.isArray(newEl)) {
        for(let j = 0, len = newEl.length; j < len; j++) {
            let subChild = newEl[j]
            newEleChange(result, subChild, oldkey)
        }
    }else{
        replaceKeyAndClone(result, newEl, oldkey)
    }
}

function replaceKeyAndClone(result, oldEl, oldkey) {
    result.push(ReactElement(
        oldEl.type,
        oldkey+'/'+(oldEl.key?oldEl.key:''),
        oldEl.ref,
        oldEl._self,
        oldEl._source,
        oldEl._owner,
        oldEl.props,
    ))
}

export {
    mapChildren as map,
};